from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List

from app.core.database import get_db
from app.api.deps import get_current_user, get_current_active_user
from app.models.user import User, UserRole
from app.schemas.message import (
    UserMessageCreate, AdminMessageCreate, MessageResponse, 
    MessageListResponse, UnreadCountResponse
)
from app.crud import message as crud_message
from app.crud import user as crud_user
from app.models.message import MessageStatus  # 新增：导入模型层的消息状态枚举

# 创建路由器
router = APIRouter()

# 用户发送消息给管理员
@router.post("/send", response_model=MessageResponse, summary="发送消息给管理员", description="普通用户向管理员发送消息")
def send_message_to_admin(
    message: UserMessageCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    用户发送消息给管理员
    
    - **title**: 消息标题
    - **content**: 消息内容
    - **parent_id**: 父消息ID（回复消息时使用，可选）
    """
    try:
        # 创建消息
        db_message = crud_message.create_user_message(db, message, current_user.id)
        
        # 构造响应
        return MessageResponse(
            id=db_message.id,
            title=db_message.title,
            content=db_message.content,
            sender_id=db_message.sender_id,
            receiver_id=db_message.receiver_id,
            sender_username=current_user.username,
            receiver_username=db_message.receiver.username,
            message_type=db_message.message_type,
            status=db_message.status,
            parent_id=db_message.parent_id,
            created_at=db_message.created_at,
            read_at=db_message.read_at
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

# 管理员发送消息给用户
# admin_send_message
@router.post("/admin/send", response_model=MessageResponse, summary="管理员发送消息", description="管理员向指定用户发送消息")
def admin_send_message(
    message: AdminMessageCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    管理员发送消息给用户
    
    - **title**: 消息标题
    - **content**: 消息内容
    - **receiver_id**: 接收者用户ID
    - **parent_id**: 父消息ID（回复消息时使用，可选）
    """
    # 检查是否为管理员
    if current_user.role != UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="权限不足，只有管理员可以执行此操作")
    
    # 检查接收者是否存在
    receiver = crud_user.get_user_by_id(db, message.receiver_id)
    if not receiver:
        raise HTTPException(status_code=404, detail="接收者不存在")
    
    # 创建消息
    try:
        db_message = crud_message.create_admin_message(db, message, current_user.id)
    except ValueError as e:
        # 将业务校验错误转为 400，避免 DB 外键约束触发 500
        raise HTTPException(status_code=400, detail=str(e))
    
    # 构造响应
    return MessageResponse(
        id=db_message.id,
        title=db_message.title,
        content=db_message.content,
        sender_id=db_message.sender_id,
        receiver_id=db_message.receiver_id,
        sender_username=current_user.username,
        receiver_username=receiver.username,
        message_type=db_message.message_type,
        status=db_message.status,
        parent_id=db_message.parent_id,
        created_at=db_message.created_at,
        read_at=db_message.read_at
    )

# 获取消息列表（会话列表，邮件收件箱效果）
@router.get("/", response_model=MessageListResponse, summary="获取会话列表", description="获取当前用户的会话列表，每个会话显示最新一条消息")
def get_conversations(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    size: int = Query(20, ge=1, le=100, description="每页会话数量，最大100条"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的会话列表（邮件收件箱效果）
    每个会话返回最新一条消息，按最新消息时间倒序排列
    """
    if current_user.role == UserRole.ADMIN:
        result = crud_message.get_admin_inbox(db, current_user.id, page, size)
    else:
        result = crud_message.get_user_inbox(db, current_user.id, page, size)

    message_responses = []
    for msg in result["messages"]:
        message_responses.append(MessageResponse(
            id=msg.id,
            title=msg.title,
            content=msg.content,
            sender_id=msg.sender_id,
            receiver_id=msg.receiver_id,
            sender_username=msg.sender.username,
            receiver_username=msg.receiver.username,
            message_type=msg.message_type,
            status=msg.status,
            parent_id=msg.parent_id,
            created_at=msg.created_at,
            read_at=msg.read_at
        ))
    
    return MessageListResponse(
        messages=message_responses,
        total=result["total"],
        page=result["page"],
        size=result["size"],
        pages=result["pages"]
    )


# 新增：普通用户与管理员的对话（自动匹配管理员）
@router.get("/conversation/admin", response_model=MessageListResponse, summary="用户与管理员对话", description="普通用户获取与管理员的完整对话历史")
def get_conversation_with_admin(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    size: int = Query(50, ge=1, le=100, description="每页消息数量，最大100条"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    普通用户与管理员的对话历史
    自动匹配可用的管理员，优先选择有历史对话的管理员
    """
    # 检查当前用户不能是管理员
    if current_user.role == UserRole.ADMIN:
        raise HTTPException(status_code=403, detail="管理员请使用 /conversation/{user_id} 接口")
    
    # 查找该用户有对话记录的管理员
    existing_admin = db.query(User).join(
        Message,
        or_(
            and_(Message.sender_id == User.id, Message.receiver_id == current_user.id),
            and_(Message.receiver_id == User.id, Message.sender_id == current_user.id)
        )
    ).filter(
        and_(
            User.role == UserRole.ADMIN,
            User.is_active == True,
            Message.is_deleted == False
        )
    ).order_by(Message.created_at.desc()).first()
    
    # 如果没有对话记录，选择第一个可用管理员
    if not existing_admin:
        existing_admin = crud_user.get_all_admins(db)
        if not existing_admin:
            raise HTTPException(status_code=404, detail="当前没有可用的管理员")
        existing_admin = existing_admin[0]  # 选择第一个管理员
    
    admin_id = existing_admin.id
    
    # 进入会话即批量标记管理员发给我的未读消息为已读
    crud_message.mark_conversation_as_read(db, current_user.id, admin_id)
    
    # 查询对话历史
    result = crud_message.get_conversation_with_user(db, current_user.id, admin_id, page, size)
    
    message_responses = []
    for msg in result["messages"]:
        message_responses.append(MessageResponse(
            id=msg.id,
            title=msg.title,
            content=msg.content,
            sender_id=msg.sender_id,
            receiver_id=msg.receiver_id,
            sender_username=msg.sender.username,
            receiver_username=msg.receiver.username,
            message_type=msg.message_type,
            status=msg.status,
            parent_id=msg.parent_id,
            created_at=msg.created_at,
            read_at=msg.read_at
        ))
    
    return MessageListResponse(
        messages=message_responses,
        total=result["total"],
        page=result["page"],
        size=result["size"],
        pages=result["pages"]
    )

# 新增：获取与特定用户的对话历史
@router.get("/conversation/{other_user_id}", response_model=MessageListResponse, summary="获取对话历史", description="获取与指定用户的完整对话历史")
def get_conversation_with_user(
    other_user_id: int,
    page: int = Query(1, ge=1, description="页码，从1开始"),
    size: int = Query(50, ge=1, le=100, description="每页消息数量，最大100条"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户与指定用户的完整对话历史（邮件对话效果）
    按时间正序排列，显示完整的对话流程
    """
    # 检查目标用户是否存在
    other_user = crud_user.get_user_by_id(db, other_user_id)
    if not other_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 进入会话即批量标记对方发给我的未读消息为已读（邮件式体验）
    crud_message.mark_conversation_as_read(db, current_user.id, other_user_id)
    
    # 再查询会话历史，返回最新已读状态
    result = crud_message.get_conversation_with_user(db, current_user.id, other_user_id, page, size)
    
    message_responses = []
    for msg in result["messages"]:
        message_responses.append(MessageResponse(
            id=msg.id,
            title=msg.title,
            content=msg.content,
            sender_id=msg.sender_id,
            receiver_id=msg.receiver_id,
            sender_username=msg.sender.username,
            receiver_username=msg.receiver.username,
            message_type=msg.message_type,
            status=msg.status,
            parent_id=msg.parent_id,
            created_at=msg.created_at,
            read_at=msg.read_at
        ))
    
    return MessageListResponse(
        messages=message_responses,
        total=result["total"],
        page=result["page"],
        size=result["size"],
        pages=result["pages"]
    )


# 获取消息详情
@router.get("/{message_id}", response_model=MessageResponse, summary="获取消息详情", description="获取指定消息的详细信息并标记为已读")
def get_message(
    message_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取消息详情并标记为已读
    
    - **message_id**: 消息ID
    
    如果是接收者查看消息，会自动标记为已读
    """
    # 获取消息
    message = crud_message.get_message_by_id(db, message_id, current_user.id)
    if not message:
        raise HTTPException(status_code=404, detail="消息不存在")
    
    # 如果是接收者查看消息，标记为已读
    if message.receiver_id == current_user.id:
        crud_message.mark_message_as_read(db, message_id, current_user.id)
        # 重新获取消息以获取更新后的状态
        message = crud_message.get_message_by_id(db, message_id, current_user.id)
    
    return MessageResponse(
        id=message.id,
        title=message.title,
        content=message.content,
        sender_id=message.sender_id,
        receiver_id=message.receiver_id,
        sender_username=message.sender.username,
        receiver_username=message.receiver.username,
        message_type=message.message_type,
        status=message.status,
        parent_id=message.parent_id,
        created_at=message.created_at,
        read_at=message.read_at
    )

# 获取未读消息数量
@router.get("/unread/count", response_model=UnreadCountResponse, summary="获取未读消息数量", description="获取当前用户的未读消息总数")
def get_unread_count(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取当前用户的未读消息数量
    
    返回未读消息的总数
    """
    count = crud_message.get_unread_count(db, current_user.id)
    return UnreadCountResponse(unread_count=count)

# 删除消息
@router.delete("/{message_id}", summary="删除消息", description="软删除指定的消息")
def delete_message(
    message_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    删除消息（软删除）
    
    - **message_id**: 要删除的消息ID
    
    只能删除自己发送或接收的消息
    """
    success = crud_message.delete_message(db, message_id, current_user.id)
    if not success:
        raise HTTPException(status_code=404, detail="消息不存在或无权限删除")
    
    return {"message": "消息删除成功"}